package com.smart4j.chapter.modules.web;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取文件列表servlet 
 */
@WebServlet("/fileListServlet")
public class FileListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	public static File[] fileList ;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1、 获取文件的存储路径
		String realPath = request.getServletContext().getRealPath(File.separator+"userfiles");
		File file = new File(realPath);
		if(!file.exists()){
			throw new RuntimeException("系统："+realPath +" 没有文件，请先上传文件!");
		}
		fileList = file.listFiles();
		for (File f : fileList) {
			System.out.println("文件名: "+f.getName() +"  相对路径： "+f.getPath() + " 绝对路径："+f.getAbsolutePath());
		}
		request.setAttribute("fileList", fileList);
		request.getRequestDispatcher("/WEB-INF/views/client/fileList.jsp").forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
